use std::fs;
use std::io::BufReader;
use std::path::Path;
use image::{GenericImageView, ImageFormat};
use log::error;
use walkdir::WalkDir;

/// 获取图片文件集合
pub fn image_files(path: &str) -> Vec<(String, String)>{
    let root = Path::new(path);
    if !root.exists() || !root.is_dir() {
        error!("Error: Invalid directory path: {}", path);
        std::process::exit(1);
    }

    let mut image_files:Vec<(String,String)> = Vec::new();
    for entry in WalkDir::new(root).into_iter().filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            let extension = entry.path().extension().and_then(|s| s.to_str());
            match extension {
                Some("jpg") | Some("jpeg") | Some("png") | Some("gif") | Some("webp") => {
                    image_files.push(
                        (entry.path().to_string_lossy().to_string(),entry.path().file_name().unwrap().to_string_lossy().to_string())
                    );
                }
                _ => {}
            }
        }
    }
    image_files
}

/// 复制文件
pub fn copy_file(src: &str, dst: &str) -> Result<(), Box<dyn std::error::Error>> {
    fs::copy(src, dst)?;
    Ok(())
}

/// 获取图片尺寸
pub fn get_image_size(image_path: &str) -> Result<(i32, i32), Box<dyn std::error::Error>> {
    // 尝试自动检测格式
    let img = match image::open(image_path) {
        Ok(img) => img,
        Err(e) => {
            error!("Error: Failed to open image {}: {}", image_path, e);
            // 如果自动检测失败，尝试根据扩展名指定格式
            let path = Path::new(image_path);
            let format = match path.extension().and_then(|s| s.to_str()) {
                Some("png") => ImageFormat::Png,
                Some("jpg") | Some("jpeg") => ImageFormat::Jpeg,
                Some("bmp") => ImageFormat::Bmp,
                Some("gif") => ImageFormat::Gif,
                Some("webp") => ImageFormat::WebP,
                _ => return Err(format!("Unsupported image format for file: {}", image_path).into()),
            };

            let file = BufReader::new(std::fs::File::open(image_path)?);
            image::load(file, format)
                .map_err(|e| format!("Failed to load image {}: {}", image_path, e))?
        }
    };

    let (width, height) = img.dimensions();
    Ok((width as i32, height as i32))
}

/// 获取目标路径下文件最大编号
pub fn get_max_num(dst: &Path) -> i32{
    let mut max_num = 0;
    for entry in WalkDir::new(dst).into_iter().filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            let filename = entry.file_name().to_string_lossy();
            let num = filename.split('_').last().unwrap().split('.').next().unwrap();
            let num = num.parse::<i32>().unwrap();
            max_num = max_num.max(num);
        }
    }
    max_num + 1
}